load(
    "@bazel_skylib//rules:common_settings.bzl",
    "string_flag",
)
load("@rules_pkg//:pkg.bzl", "pkg_tar")
load("@rules_erlang//:dialyze.bzl", "plt")
load("@rules_erlang//:shell.bzl", "shell")
load("@rules_erlang//:erl_eval.bzl", "erl_eval")
load("//bazel/elixir:iex_eval.bzl", "iex_eval")
load(":rabbitmq_home.bzl", "rabbitmq_home")
load(":rabbitmq_run.bzl", "rabbitmq_run", "rabbitmq_run_command")
load(":rabbitmqctl.bzl", "rabbitmqctl")
load(":dist.bzl", "package_generic_unix", "source_archive")
load(":rabbitmq.bzl", "all_plugins")

exports_files([
    "scripts/bazel/rabbitmq-run.sh",
    "scripts/bazel/rabbitmq-run.bat",
])

config_setting(
    name = "debug_build",
    values = {
        "compilation_mode": "dbg",
    },
)

string_flag(
    name = "elixir_home",
    build_setting_default = "",
    visibility = ["//visibility:public"],
)

plt(
    name = "base_plt",
    visibility = ["//visibility:public"],
)

PLUGINS = all_plugins(
    rabbitmq_workspace = "",
)

rabbitmq_home(
    name = "broker-home",
    plugins = PLUGINS,
)

rabbitmq_run(
    name = "rabbitmq-run",
    home = ":broker-home",
    visibility = ["//visibility:public"],
)

# Allow us to `bazel run broker`
# for the equivalent of `make run-broker`
rabbitmq_run_command(
    name = "broker",
    rabbitmq_run = ":rabbitmq-run",
    subcommand = "run-broker",
)

# Allow us to `bazel run start-cluster`
# for the equivalent of `make start-cluster`
rabbitmq_run_command(
    name = "start-cluster",
    rabbitmq_run = ":rabbitmq-run",
    subcommand = "start-cluster",
)

# Allow us to `bazel run stop-cluster`
# for the equivalent of `make stop-cluster`
rabbitmq_run_command(
    name = "stop-cluster",
    rabbitmq_run = ":rabbitmq-run",
    subcommand = "stop-cluster",
)

# `bazel run rabbitmqctl`
rabbitmqctl(
    name = "rabbitmqctl",
    home = ":broker-home",
    visibility = ["//visibility:public"],
)

rabbitmqctl(
    name = "rabbitmq-diagnostics",
    home = ":broker-home",
)

rabbitmqctl(
    name = "rabbitmq-plugins",
    home = ":broker-home",
)

shell(
    name = "repl",
    deps = PLUGINS,
)

erl_eval(
    name = "otp_version",
    outs = ["otp_version.txt"],
    expression = """{ok, Version} = file:read_file(filename:join([code:root_dir(), "releases", erlang:system_info(otp_release), "OTP_VERSION"])), file:write_file(os:getenv("OUTS"), Version), halt().""",
)

iex_eval(
    name = "elixir_version",
    outs = ["elixir_version.txt"],
    expression = """File.write!(System.get_env("OUTS"), System.version()); System.halt()""",
)

filegroup(
    name = "root-licenses",
    srcs = glob(
        ["LICENSE*"],
        exclude = [
            "LICENSE.md",
            "LICENSE.txt",
        ],
    ),
    visibility = ["//visibility:public"],
)

pkg_tar(
    name = "scripts-tar",
    srcs = [
        "scripts/bash_autocomplete.sh",
        "scripts/rabbitmq-script-wrapper",
        "scripts/rabbitmqctl-autocomplete.sh",
        "scripts/zsh_autocomplete.sh",
    ],
    package_dir = "scripts",
    visibility = ["//visibility:public"],
)

pkg_tar(
    name = "release-notes-tar",
    srcs = glob([
        "release-notes/*.md",
        "release-notes/*.txt",
    ]),
    package_dir = "release-notes",
    visibility = ["//visibility:public"],
)

package_generic_unix(plugins = PLUGINS)

source_archive(plugins = PLUGINS)

genrule(
    name = "test-logs",
    outs = ["open-test-logs.sh"],
    cmd = """set -euo pipefail
cat << 'EOF' > $@
#!/bin/bash
set -euo pipefail
if [ $$# -eq 0 ]; then
    echo "Usage: bazel run test-logs TEST_LABEL [shard_index]"
    exit 1
fi

RELATIVE=$${1#//}
PACKAGE=$${RELATIVE%%:*}
SUITE=$${RELATIVE##*:}
OUTPUT_DIR=test.outputs
if [ $$# -gt 1 ]; then
    OUTPUT_DIR=shard_$$2_of_*/test.outputs
fi
cd "bazel-testlogs/$$PACKAGE/$$SUITE/$$OUTPUT_DIR"
if [ -f outputs.zip ]; then
    unzip -u outputs.zip
fi
set +e
open index.html
rc=$$?
set -e
if [[ $$rc -eq 3 ]]; then
  # For xdg-open exit code 3 means "A required tool could not be found." That is, there is no browser.
  echo "Open your browser at http://$$(hostname -s):8000/index.html"
  python -m http.server 8000
fi
EOF
""",
    executable = True,
)

genrule(
    name = "remote-test-logs",
    outs = ["open-remote-test-logs.sh"],
    cmd = """set -euo pipefail
cat << 'EOF' > $@
#!/bin/bash
set -euo pipefail
if [ $$# -eq 0 ]; then
    echo "Usage: bazel run remote-test-logs TEST_LABEL [shard_index]"
    exit 1
fi

RELATIVE=$${1#//}
PACKAGE=$${RELATIVE%%:*}
SUITE=$${RELATIVE##*:}
OUTPUT_DIR=test.outputs
if [ $$# -gt 1 ]; then
    OUTPUT_DIR=shard_$$2_of_*/test.outputs
fi
TESTLOGS=$$(echo $$(bazel info output_path)/k8-*/testlogs)
cd "$$TESTLOGS/$$PACKAGE/$$SUITE/$$OUTPUT_DIR" && unzip -u outputs.zip
open index.html
EOF
""",
    executable = True,
)

genrule(
    name = "test-node-data",
    outs = ["open-test-node-data.sh"],
    cmd = """set -euo pipefail
cat << 'EOF' > $@
    set -euo pipefail
    if [ $$# -eq 0 ]; then
        echo "Usage: bazel run test-node-data TEST_LABEL [shard_index]"
        exit 1
    fi

    RELATIVE=$${1#//}
    PACKAGE=$${RELATIVE%%:*}
    SUITE=$${RELATIVE##*:}
    OUTPUT_DIR=test.outputs
    if [ $$# -gt 1 ]; then
        OUTPUT_DIR=shard_$$2_of_*/test.outputs
    fi
    cd bazel-testlogs/$$PACKAGE/$$SUITE/$$OUTPUT_DIR
    if [ -f outputs.zip ]; then
        unzip -u outputs.zip
    fi
    open index.html
    open ct_run.*/deps.*/run.*/log_private
EOF
""",
    executable = True,
)

# NOTE: this rule may not work properly if --remote_download_minimal has been used,
#       which is currently the default for remote runs
genrule(
    name = "remote-test-node-data",
    outs = ["open-remote-test-node-data.sh"],
    cmd = """set -euo pipefail
cat << 'EOF' > $@
    set -euo pipefail
    if [ $$# -eq 0 ]; then
        echo "Usage: bazel run remote-test-node-data TEST_LABEL [shard_index]"
        exit 1
    fi

    RELATIVE=$${1#//}
    PACKAGE=$${RELATIVE%%:*}
    SUITE=$${RELATIVE##*:}
    OUTPUT_DIR=test.outputs
    if [ $$# -gt 1 ]; then
        OUTPUT_DIR=shard_$$2_of_*/test.outputs
    fi
    TESTLOGS=$$(echo $$(bazel info output_path)/k8-*/testlogs)
    cd $$TESTLOGS/$$PACKAGE/$$SUITE/$$OUTPUT_DIR && unzip -u outputs.zip
    open index.html
    open ct_run.*/deps.*/run.*/log_private
EOF
""",
    executable = True,
)
